﻿using System;
using System.Configuration;
using System.Linq;
using System.Text.RegularExpressions;
using EntityFrameworkExtension.Interface;
using MainProcessor.Interface;

namespace MainProcessor.Caching
{
    public class RepositoryFlush : IRepositoryFlush
    {
        private readonly IEfContext efEntities;
        private readonly string database;
        private readonly string server;

        public RepositoryFlush(IEfContext efEntities)
        {
            this.efEntities = efEntities;
            database = ConfigurationManager.AppSettings["DatabaseName"];
            server = ConfigurationManager.AppSettings["ServerName"];
        }

        public Guid CreateGuidIdMapping<T>(int inputId) where T : class, IGuidIntMapping, IEquatable<T>, new()
        {
            using (efEntities.Open(server, database))
            {
                var result = (from x in efEntities.GetObjectList<T>()
                              where x.Id == inputId
                              select x); // this will call the whole table from the database and filter on the server

                if (result.Any())
                    return result.First().Guid;

                var entry = new T { Guid = Guid.NewGuid(), Id = inputId }; // use an injected class to create the guid for unit testing

                efEntities.AddToObjectList(entry);
                efEntities.SaveChanges();
                return entry.Guid;
            }
        }

      
   }
}
